package com.changgou.system.util;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

/**
 * JWT工具类
 */
public class JwtUtil {

    //设置有效期
    public static final Long JWT_TTL =3600000L;// 60*60*1000毫秒
    //设置密钥明文
    public static final String JWT_KEY="itcast";




    public static String createJWT (String id,String subject,Long ttlMillis){
        //签名算法使用HS256
        SignatureAlgorithm signatureAlgorithm=SignatureAlgorithm.HS256;
        long nowMillis=System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis==null){
            ttlMillis=JwtUtil.JWT_TTL;
        }
        long expMillis=nowMillis+ttlMillis;
        Date expDate = new Date(expMillis);
        SecretKey secretKey=generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)//唯一id
                .setSubject(subject)//主题 主要是json数据
                .setIssuer("admin")// 签发者
                .setIssuedAt(now) //签发时间
                .signWith(signatureAlgorithm, secretKey)//设置签名算法HS256对称加密,第二个参数是密钥
                .setExpiration(expDate);//设置过期时间
        return builder.compact();

    }


    /**
     * 生成加密后的密钥secretkey
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodekey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKeySpec key = new SecretKeySpec(encodekey, 0, encodekey.length, "AES");
        return key;
    }

}
